<?php

namespace backend\modules\rbac\models;

use mdm\admin\models\User as MdmUser;
use yii\behaviors\TimestampBehavior;

/**
 * User model
 */
class User extends MdmUser
{
    private $_assignments = [];
    public $password_two = '';

    /**
     * @inheritdoc
     */
    public function rules()
    {
        $rules = parent::rules();
        $rules[] = [['id','username', 'roles'], 'safe'];
        $rules[] = [['password','password_two','email'], 'string'];
        return $rules;
    }

    public function attributeLabels()
    {
        return [
            'id'=>'ID',
            'username'=>'用户名',
            'email'=>'邮箱',
            'roles' => '角色',
            'permissions' => '权限',
            'password'=>'密码',
            'password_two'=>'再次确认',
        ];
    }

    public function getPassword()
    {
        return '';
    }

    public function setPassword($value)
    {
        //没有密码就别修改了
        if($value){
            parent::setPassword($value);
        }
    }

    public function getRoles()
    {
        return $this->_getAssignments();
    }

    public function setRoles($value)
    {
        $this->roles = $value?$value:[];
    }

    public function getPermissions()
    {
        return $this->_getAssignments();
    }

    public function setPermissions($value)
    {
        $this->permissions = $value?$value:[];
    }

    private function _getAssignments()
    {
        if($this->_assignments){
            return $this->_assignments;
        }
        $this->_assignments = AuthAssignment::find()->where(['user_id'=>$this->getId()])->select('item_name')->column();
        return $this->_assignments;
    }

    public static function saveAssignment($userId, $assignment = [])
    {
        $userId = strval($userId);
        $old = AuthAssignment::find()->where(['user_id'=>$userId])->select(['item_name'])->column();
        $cut = array_diff($old, $assignment);
        $add = array_diff($assignment, $old);
        //保存一下授权
        AuthAssignment::getDb()->transaction(function () use($cut, $add, $userId){
            AuthAssignment::deleteAll(['user_id'=>$userId, 'item_name'=>$cut]);
            $obj = new AuthAssignment();
            foreach ($add as $value){
                $obj->setIsNewRecord(true);
                $obj->item_name = $value;
                $obj->user_id = $userId;
                $obj->save();
            }
        });
    }
}
